<?php
require_once 'config.php';

header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    exit(0);
}

// 错误报告
error_reporting(E_ALL);
ini_set('display_errors', 1);

// 日志记录
function writeLog($message, $type = 'INFO') {
    $logFile = __DIR__ . '/logs/app-' . date('Y-m-d') . '.log';
    $dir = dirname($logFile);
    
    if (!is_dir($dir)) {
        mkdir($dir, 0755, true);
    }
    
    $timestamp = date('Y-m-d H:i:s');
    $logMessage = "[$timestamp] [$type] $message\n";
    file_put_contents($logFile, $logMessage, FILE_APPEND);
}

// 发送微信推送
function sendWxPush($config, $message) {
    $url = $config['api_url'];
    $data = [
        'appToken' => $config['app_token'],
        'content' => $message,
        'contentType' => 1,
        'uids' => [$config['uid']]
    ];

    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
    curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $error = curl_error($ch);
    curl_close($ch);

    if ($error) {
        throw new Exception("推送请求失败: $error");
    }

    if ($httpCode !== 200) {
        throw new Exception("推送服务响应异常: HTTP $httpCode");
    }

    $result = json_decode($response, true);
    if (!$result || $result['code'] !== 1000) {
        throw new Exception("推送失败: " . ($result['msg'] ?? '未知错误'));
    }

    return true;
}

// 获取配置
function getConfig() {
    try {
        $conn = connectDB();
        $conn->begin_transaction();
        
        $sql = "SELECT * FROM configs ORDER BY id DESC LIMIT 1";
        $result = $conn->query($sql);
        
        if (!$result) {
            throw new Exception("获取配置失败: " . $conn->error);
        }
        
        $config = $result->fetch_assoc();
        
        // 获取消息模板
        $templates = [];
        $sql = "SELECT * FROM message_templates WHERE is_active = 1 ORDER BY sort_order ASC";
        $result = $conn->query($sql);
        while ($row = $result->fetch_assoc()) {
            $templates[] = $row;
        }
        
        $conn->commit();
        $conn->close();
        
        writeLog("配置获取成功");
        
        return [
            'success' => true,
            'data' => [
                'phone' => $config['phone'],
                'wxPusher' => [
                    'appToken' => $config['app_token'],
                    'uids' => [$config['uid']],
                    'apiUrl' => $config['api_url']
                ],
                'notification' => [
                    'cooldown' => intval($config['cooldown']),
                    'defaultMessage' => $config['default_message'],
                    'templates' => $templates
                ]
            ]
        ];
    } catch (Exception $e) {
        if (isset($conn)) {
            $conn->rollback();
            $conn->close();
        }
        writeLog("获取配置异常: " . $e->getMessage(), 'ERROR');
        return [
            'success' => false,
            'error' => $e->getMessage()
        ];
    }
}

// 保存配置
function saveConfig($data) {
    try {
        // 数据验证
        if (empty($data['phone']) || !preg_match('/^1[3-9]\d{9}$/', $data['phone'])) {
            throw new Exception('无效的电话号码');
        }
        
        if (empty($data['notification']['cooldown']) || 
            $data['notification']['cooldown'] < SYSTEM_CONFIG['min_cooldown'] || 
            $data['notification']['cooldown'] > SYSTEM_CONFIG['max_cooldown']) {
            throw new Exception('无效的冷却时间');
        }
        
        if (empty($data['notification']['defaultMessage'])) {
            throw new Exception('默认消息不能为空');
        }
        
        if (empty($data['wxPusher']['appToken'])) {
            throw new Exception('AppToken不能为空');
        }
        
        if (empty($data['wxPusher']['uids']) || !is_array($data['wxPusher']['uids'])) {
            throw new Exception('无效的UID');
        }
        
        if (empty($data['wxPusher']['apiUrl']) || !filter_var($data['wxPusher']['apiUrl'], FILTER_VALIDATE_URL)) {
            throw new Exception('无效的API地址');
        }
        
        $conn = connectDB();
        $conn->begin_transaction();
        
        // 获取当前配置ID
        $result = $conn->query("SELECT id FROM configs ORDER BY id DESC LIMIT 1");
        if (!$result) {
            throw new Exception("获取配置失败: " . $conn->error);
        }
        
        $configId = $result->num_rows > 0 ? $result->fetch_assoc()['id'] : null;
        
        if ($configId) {
            // 更新现有配置
            $stmt = $conn->prepare("UPDATE configs SET 
                phone = ?, 
                cooldown = ?, 
                default_message = ?,
                app_token = ?,
                uid = ?,
                api_url = ? 
                WHERE id = ?");
            
            $phone = $data['phone'];
            $cooldown = $data['notification']['cooldown'];
            $defaultMessage = $data['notification']['defaultMessage'];
            $appToken = $data['wxPusher']['appToken'];
            $uid = $data['wxPusher']['uids'][0];
            $apiUrl = $data['wxPusher']['apiUrl'];
            
            $stmt->bind_param("sissssi", $phone, $cooldown, $defaultMessage, $appToken, $uid, $apiUrl, $configId);
        } else {
            // 如果没有配置，则插入新配置
            $stmt = $conn->prepare("INSERT INTO configs (phone, cooldown, default_message, app_token, uid, api_url) 
                VALUES (?, ?, ?, ?, ?, ?)");
            
            $phone = $data['phone'];
            $cooldown = $data['notification']['cooldown'];
            $defaultMessage = $data['notification']['defaultMessage'];
            $appToken = $data['wxPusher']['appToken'];
            $uid = $data['wxPusher']['uids'][0];
            $apiUrl = $data['wxPusher']['apiUrl'];
            
            $stmt->bind_param("sissss", $phone, $cooldown, $defaultMessage, $appToken, $uid, $apiUrl);
        }
        
        if (!$stmt->execute()) {
            throw new Exception(($configId ? "更新" : "插入") . "配置失败: " . $stmt->error);
        }
        
        $stmt->close();
        $conn->commit();
        $conn->close();
        
        writeLog("配置" . ($configId ? "更新" : "插入") . "成功");
        return ['success' => true];
    } catch (Exception $e) {
        if (isset($conn)) {
            $conn->rollback();
            $conn->close();
        }
        writeLog("保存配置异常: " . $e->getMessage(), 'ERROR');
        return [
            'success' => false,
            'error' => $e->getMessage()
        ];
    }
}

// 验证密码
function verifyPassword($password) {
    try {
        $conn = connectDB();
        $sql = "SELECT admin_password FROM configs ORDER BY id DESC LIMIT 1";
        $result = $conn->query($sql);
        
        if (!$result) {
            throw new Exception("获取密码失败: " . $conn->error);
        }
        
        $config = $result->fetch_assoc();
        $conn->close();
        
        $verified = $password === $config['admin_password'];
        writeLog("密码验证" . ($verified ? "成功" : "失败"));
        
        return [
            'success' => $verified
        ];
    } catch (Exception $e) {
        writeLog("密码验证异常: " . $e->getMessage(), 'ERROR');
        return [
            'success' => false,
            'error' => $e->getMessage()
        ];
    }
}

// 修改密码
function changePassword($currentPassword, $newPassword) {
    try {
        // 先验证当前密码
        $verify = verifyPassword($currentPassword);
        if (!$verify['success']) {
            throw new Exception("当前密码错误");
        }
        
        if (strlen($newPassword) < 6) {
            throw new Exception("新密码长度不能少于6位");
        }
        
        $conn = connectDB();
        $conn->begin_transaction();
        
        $stmt = $conn->prepare("UPDATE configs SET admin_password = ? WHERE id = (SELECT id FROM (SELECT id FROM configs ORDER BY id DESC LIMIT 1) as t)");
        $stmt->bind_param("s", $newPassword);
        
        if (!$stmt->execute()) {
            throw new Exception("修改密码失败: " . $stmt->error);
        }
        
        $stmt->close();
        $conn->commit();
        $conn->close();
        
        writeLog("密码修改成功");
        return ['success' => true];
    } catch (Exception $e) {
        if (isset($conn)) {
            $conn->rollback();
            $conn->close();
        }
        writeLog("修改密码异常: " . $e->getMessage(), 'ERROR');
        return [
            'success' => false,
            'error' => $e->getMessage()
        ];
    }
}

// 获取通知记录
function getNotifications() {
    try {
        $conn = connectDB();
        $sql = "SELECT * FROM notifications ORDER BY timestamp DESC LIMIT 50";
        $result = $conn->query($sql);
        
        if (!$result) {
            throw new Exception("获取通知记录失败: " . $conn->error);
        }
        
        $notifications = [];
        while ($row = $result->fetch_assoc()) {
            $notifications[] = $row;
        }
        
        $conn->close();
        
        writeLog("获取通知记录成功，共" . count($notifications) . "条");
        return [
            'success' => true,
            'data' => $notifications
        ];
    } catch (Exception $e) {
        writeLog("获取通知记录异常: " . $e->getMessage(), 'ERROR');
        return [
            'success' => false,
            'error' => $e->getMessage()
        ];
    }
}

// 添加通知记录
function addNotification($message) {
    try {
        $conn = connectDB();
        $conn->begin_transaction();
        
        // 获取配置
        $sql = "SELECT * FROM configs ORDER BY id DESC LIMIT 1";
        $result = $conn->query($sql);
        if (!$result || $result->num_rows === 0) {
            throw new Exception("获取配置失败");
        }
        $config = $result->fetch_assoc();
        
        // 发送微信推送
        $success = sendWxPush($config, $message);
        
        // 记录通知
        $stmt = $conn->prepare("INSERT INTO notifications (message, status) VALUES (?, ?)");
        $status = $success ? 1 : 0;
        $stmt->bind_param("si", $message, $status);
        
        if (!$stmt->execute()) {
            throw new Exception("添加通知记录失败: " . $stmt->error);
        }
        
        $stmt->close();
        $conn->commit();
        $conn->close();
        
        writeLog("添加通知记录成功");
        return ['success' => true];
    } catch (Exception $e) {
        if (isset($conn)) {
            $conn->rollback();
            $conn->close();
        }
        writeLog("添加通知记录异常: " . $e->getMessage(), 'ERROR');
        return [
            'success' => false,
            'error' => $e->getMessage()
        ];
    }
}

// 删除通知记录
function deleteNotification($id) {
    try {
        $conn = connectDB();
        $conn->begin_transaction();
        
        $stmt = $conn->prepare("DELETE FROM notifications WHERE id = ?");
        $stmt->bind_param("i", $id);
        
        if (!$stmt->execute()) {
            throw new Exception("删除通知记录失败: " . $stmt->error);
        }
        
        $stmt->close();
        $conn->commit();
        $conn->close();
        
        writeLog("删除通知记录成功 ID: $id");
        return ['success' => true];
    } catch (Exception $e) {
        if (isset($conn)) {
            $conn->rollback();
            $conn->close();
        }
        writeLog("删除通知记录异常: " . $e->getMessage(), 'ERROR');
        return [
            'success' => false,
            'error' => $e->getMessage()
        ];
    }
}

// 获取统计数据
function getStats() {
    try {
        $conn = connectDB();
        
        // 获取今日通知数量
        $sql = "SELECT COUNT(*) as today FROM notifications WHERE DATE(timestamp) = CURDATE()";
        $result = $conn->query($sql);
        $today = $result->fetch_assoc()['today'];
        
        // 获取总通知数量
        $sql = "SELECT COUNT(*) as total FROM notifications";
        $result = $conn->query($sql);
        $total = $result->fetch_assoc()['total'];
        
        $conn->close();
        
        writeLog("获取统计数据成功");
        return [
            'success' => true,
            'data' => [
                'today' => $today,
                'total' => $total
            ]
        ];
    } catch (Exception $e) {
        writeLog("获取统计数据异常: " . $e->getMessage(), 'ERROR');
        return [
            'success' => false,
            'error' => $e->getMessage()
        ];
    }
}

// 发送测试消息
function sendTestNotification() {
    try {
        $conn = connectDB();
        
        // 获取配置
        $sql = "SELECT * FROM configs ORDER BY id DESC LIMIT 1";
        $result = $conn->query($sql);
        if (!$result || $result->num_rows === 0) {
            throw new Exception("获取配置失败");
        }
        $config = $result->fetch_assoc();
        
        // 发送测试消息
        $message = "这是一条测试消息 - " . date('Y-m-d H:i:s');
        $success = sendWxPush($config, $message);
        
        $conn->close();
        
        writeLog("发送测试消息成功");
        return ['success' => true];
    } catch (Exception $e) {
        writeLog("发送测试消息异常: " . $e->getMessage(), 'ERROR');
        return [
            'success' => false,
            'error' => $e->getMessage()
        ];
    }
}

// 处理请求
$action = isset($_GET['action']) ? $_GET['action'] : '';
$postData = json_decode(file_get_contents('php://input'), true);

writeLog("收到请求: " . $action);

try {
    switch ($action) {
        case 'getConfig':
            echo json_encode(getConfig());
            break;
            
        case 'saveConfig':
            if (empty($postData)) {
                throw new Exception('无效的配置数据');
            }
            echo json_encode(saveConfig($postData));
            break;
            
        case 'verifyPassword':
            if (empty($postData['password'])) {
                throw new Exception('请输入密码');
            }
            echo json_encode(verifyPassword($postData['password']));
            break;
            
        case 'changePassword':
            if (empty($postData['currentPassword']) || empty($postData['newPassword'])) {
                throw new Exception('请输入完整的密码信息');
            }
            echo json_encode(changePassword($postData['currentPassword'], $postData['newPassword']));
            break;
            
        case 'getNotifications':
            echo json_encode(getNotifications());
            break;
            
        case 'addNotification':
            if (empty($postData['message'])) {
                throw new Exception('无效的通知内容');
            }
            echo json_encode(addNotification($postData['message']));
            break;
            
        case 'deleteNotification':
            if ($_SERVER['REQUEST_METHOD'] !== 'DELETE') {
                throw new Exception('无效的请求方法');
            }
            if (empty($_GET['id'])) {
                throw new Exception('缺少通知ID');
            }
            echo json_encode(deleteNotification($_GET['id']));
            break;
            
        case 'getStats':
            echo json_encode(getStats());
            break;
            
        case 'testNotification':
            echo json_encode(sendTestNotification());
            break;
            
        default:
            throw new Exception('未知的操作');
    }
} catch (Exception $e) {
    writeLog("请求处理异常: " . $e->getMessage(), 'ERROR');
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'error' => $e->getMessage()
    ]);
}